package com.yyk.yiliao.util.pay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import com.yyk.yiliao.bean.AlipayPayment_Info;
import com.yyk.yiliao.ui.gongyong.activity.PayFailure_Activity;
import com.yyk.yiliao.ui.gongyong.activity.PaySuccess_Activity;
import com.yyk.yiliao.util.OkHttp3Utlis;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.pay.zfb.PayResult;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 支付宝支付
 */

public class PayUtils {

    private Context mContext;
    private static volatile PayUtils mPayUtils = null;

    public PayUtils(Context context) {
        this.mContext = context;

    }

    public static PayUtils getInstance(Context context) {
        if (mPayUtils == null) {
            synchronized (PayUtils.class) {
                if (mPayUtils == null) mPayUtils = new PayUtils(context);
            }
        }
        return mPayUtils;
    }

    /**
     * 支付宝支付回掉
     */
    public interface AlipayBack {
        void payBack(boolean status);
    }

    public AlipayBack alipayBack;

    public void setAlipayBack(AlipayBack alipayBack) {
        this.alipayBack = alipayBack;
    }

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2018072560804323";
    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC9RJFe/KX0hizg\n" +
            "0g1Zfyog40jlN+3KSu7jbNAJdFlNyUYkNpW8H8lvV+U6Q/g6KgdAuGEZsAxLvGKd\n" +
            "Wx4cISZarg3UpYdpsw43KTVdSIFAybXDakPq7Wr9ahUbEvtKmDR2qZJHPh/GsR5C\n" +
            "s1xLMH9vaHhRmaJCjKim7O7HeQNjuQVx+MLX/OuTOtHt331aldnC8tF7a/2LZNu1\n" +
            "+Nt8V5YdMb+a7qiWsZ3TPcW4q5aGAPALNv0c2X3nd+PWNNFZPuL3q5+03czaAmY4\n" +
            "+F1yl12A2H8EDb6kZOyFmQiUlUia3lk3bgUw5N6lZ1pzYK32lQbQCxbHRwWf0HIB\n" +
            "+ietLYyXAgMBAAECggEAEeKV3iT/xbCcMw6GZmum3n6717VGSjR0iJcyvYH6Imif\n" +
            "sTJbSfCzB0uGBNCBd3WbQ9loi5XgQ5Pkubvvh3b2eeEyu2J8/lcGQ94oBc2hMS8e\n" +
            "dv3mtx+CWboZjnpntq/VXVU+1m6fcBYyptjuIsjNcgisPgHHnIRQN53yHnVoBZc/\n" +
            "u0nwwXpUYidwylrjBxVT2rraKfQz6PKHUzj/t1Ax7Z4o+v16Z6r2oQW5biukv8I/\n" +
            "4SPxSBBvkcGQgXF3MgEGWjzsXZG14LTcGECRmHXhnsYHbxPd38NVGLKv9Kq9vERe\n" +
            "Q94o1wDZbSFd1x3beEbWw9ELpFGM9Gl6pvkjLmOJYQKBgQDdcbcBVdiMkR5ZqixD\n" +
            "akowINk+bRtKBKH/Pk9rLvq+kzbctkfqhotKFwKY/d9697kHuAnnz6WKc1zwqFh7\n" +
            "wQg4dJIUXN7+oOhdbYiAifJH+eP6A1LVfD4OrJz7DUVlNpNQ0EUUGtAp5IV14xfp\n" +
            "T5ouwV5FpYukbYTVjIFd1s7vkQKBgQDazXedvA06Z674auaiO6327lZisxxVOwOA\n" +
            "QT++FeRgP4dIiN0/5YQbw/znCjPd59uzxPv1GYsawdAzqh7xdPw9/dv39P123Foy\n" +
            "lO1o3+ctuTxFoPsxGTh7YbHomZh1mbI6s0j9cHTWkWUOawLCqZzXiMBEh5QOkLuB\n" +
            "/AhN2JJ1pwKBgQDQrN4ltf3wyLfvCvvXM4xhujK+LxbuM1ttKgyxFn5XpGaoqmUu\n" +
            "zkboNLLP9TzpphOJAJblCboXtAq7BgkL5aWXfdJCuhmxnXQaxqNBbb0Qsp1w9jzS\n" +
            "zNe2AFeWBLWGYV2FZB4Uigfr0lsp8iyQQeErejEaNJxZAJOSoWsvQMOU4QKBgQDU\n" +
            "nOHGCY0FGulgBWjVbo6OK20P/aHjhDPTthO9n0JK8JCBwFTWGS21WU3wJ+7ci8fm\n" +
            "uNxogAi22Gx7N61XzeiqSHsuSAbgMCEJk8Paq+/Vc3EI6/QK8sn6wqUBM/d9Fvuk\n" +
            "pMChXVx7f88mIoANLon0urKyJNiPCr7aAVEEbBVtcwKBgGpclIamFp0FFgl79Dmk\n" +
            "az8IrulPpLG2ZE2pnMKhyB2QewNCHXbjNphbuWuJCfbj8eScL2tyDRKStgurCI2B\n" +
            "YEy17UpRAS3NuRfZ0ZD/Kqh87PVFFaVPCepeXm/m7cG6R1FyJ7YuEZAJ9eXFxK6F\n" +
            "SYLNXnh1XUt5h7sCrfU+94T6";

    public static final String RSA_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;

    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask((Activity) mContext);
        String version = payTask.getVersion();
        Toast.makeText(mContext, version, Toast.LENGTH_SHORT).show();
    }

    /**
     * 支付宝支付业务
     *
     * @param
     */
    public void payV2(float qian, String dingdanhao) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(mContext).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {

                        }
                    }).show();
            return;
        }
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("total_amount", qian + "");
        hashMap.put("out_trade_no", dingdanhao + "");
        hashMap.put("body", "");
        OkHttp3Utlis.getIntance().postOkhttp(ApiService.BASE_URL + "/mobile/alipay/getSign", hashMap, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String orderInfoTest = response.body().string().trim();
                Logger.e("orderInfoTest:" + orderInfoTest);
                Gson gson = new Gson();
                AlipayPayment_Info pay_info = gson.fromJson(orderInfoTest, AlipayPayment_Info.class);
                PayTask alipay = new PayTask((Activity) mContext);
                Map<String, String> result = alipay.payV2(pay_info.getSign(), true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.showShort(null, "支付成功");

                        if (alipayBack != null) {
                            alipayBack.payBack(true);
                        }
                    } else if (TextUtils.equals(resultStatus, "5000")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.showShort(null, "请忽重复订单");
                        if (alipayBack != null) {
                            alipayBack.payBack(false);
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.showShort(null, "支付失败");

                        if (alipayBack != null) {
                            alipayBack.payBack(false);
                        }
                    }
                    break;
                }

            }
        }

        ;
    };

}
